using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace MobileEditor
{
	public partial class EditorPage : TabPage
	{
		private BufferSettings _bufferSettings;
		private bool _changed;
		private TextBox _editor;
		private GlobalSettings _globalSettings;


		public EditorPage()
		{
			InitializeComponent();
		}

		public EditorPage(BufferSettings bufferSettings)
			: this()
		{
			BufferSettings = bufferSettings;
			Text = BufferSettings.Title;

			Panel p = new Panel();
			p.Width = 20;
			p.Dock = DockStyle.Left;
			p.Paint += new PaintEventHandler(p_Paint);
			Controls.Add(p);

			Editor = new TextBox();
			Editor.BringToFront();

			OpenFile(bufferSettings.Filename);
		}

		void p_Paint(object sender, PaintEventArgs e)
		{
	//    //With MyRichTextBox
	// Single font_height;// Dim font_height As Single 
	//    Editor.
	// font_height = Editor.GetPositionFromCharIndex(.GetFirstCharIndexFromLine(2)).Y _
	//       - .GetPositionFromCharIndex(.GetFirstCharIndexFromLine(1)).Y
	// If font_height = 0 Then Exit Sub

	// //'Get the first line index and location
	// Dim first_index As Integer
	// Dim first_line As Integer
	// Dim first_line_y As Integer
	// first_index = .GetCharIndexFromPosition(New _
	//       Point(0, g.VisibleClipBounds.Y + font_height / 3))
	// first_line = .GetLineFromCharIndex(first_index)
	// first_line_y = .GetPositionFromCharIndex(first_index).Y

	// //'Print on the PictureBox the visible line numbers of the RichTextBox
	// g.Clear(Control.DefaultBackColor)
	// Dim i As Integer = first_line
	// Dim y As Single
	// Do While y < g.VisibleClipBounds.Y + g.VisibleClipBounds.Height
	//  y = first_line_y + 2 + font_height * (i - first_line - 1)
	//  g.DrawString((i).ToString, .Font, Brushes.DarkBlue, MyPictureBox.Width _
	//        - g.MeasureString((i).ToString, .Font).Width, y)
	//  i += 1
	// Loop
	// //'Debug.WriteLine("Finished: " & firstLine + 1 & " " & i - 1)
	////End With
		}


		public BufferSettings BufferSettings
		{
			get { return _bufferSettings; }
			set
			{
				if (_bufferSettings != null)
				{
					_bufferSettings.FilenameChanged -= new EventHandler(_bufferSettings_FilenameChanged);
				}
				_bufferSettings = value;
				if (_bufferSettings != null)
				{
					_bufferSettings.FilenameChanged += new EventHandler(_bufferSettings_FilenameChanged);
				}
			}
		}

		public bool Changed
		{
			get { return _changed; }
			set { _changed = value; }
		}

		public TextBox Editor
		{
			get { return _editor; }
			set
			{
				if (_editor != null)
				{
					_editor.TextChanged -= new EventHandler(_editor_TextChanged);
					if (Controls.Contains(_editor)) Controls.Remove(_editor);
				}
				_editor = value;
				if (_editor != null)
				{
					_editor.AcceptsReturn = true;
					_editor.AcceptsTab = true;
					_editor.Dock = DockStyle.Fill;
					_editor.HideSelection = false;
					_editor.Multiline = true;
					_editor.ScrollBars = ScrollBars.Both;
					_editor.WordWrap = true;
					_editor.TextChanged += new EventHandler(_editor_TextChanged);
					if (!Controls.Contains(_editor)) Controls.Add(_editor);
				}
			}
		}
		
		public GlobalSettings GlobalSettings
		{
			get { return _globalSettings; }
			set { _globalSettings = value; }
		}

		public bool WordWrap
		{
			get { return Editor.WordWrap; }
			set { Editor.WordWrap = value; }
		}


		public bool CloseFile()
		{
			bool close;
			if (Changed)
			{
				DialogResult result = MessageBox.Show("Save changes?", Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
				switch (result)
				{
					case DialogResult.Cancel: close = false; break;
					case DialogResult.Yes: SaveFile(); close = true; break;
					default: close = true; break;
				}
			}
			else close = true;
			return close;
		}
		
		private void OpenFile(string filename)
		{
			if (File.Exists(filename))
			{
				using (StreamReader reader = new StreamReader(filename))
				{
					BufferSettings.Encoding = reader.CurrentEncoding;
					Editor.Text = reader.ReadToEnd();
				}
				BufferSettings.Filename = filename;
				Text = Path.GetFileName(filename);
			}
		}

		public void SaveFile()
		{
			if (BufferSettings.Filename != null && BufferSettings.Filename.Length > 0) SaveFile(BufferSettings.Filename);
			else SaveFileAs();
		}

		private void SaveFile(string filename)
		{
			if (File.Exists(filename) && GlobalSettings.General.CreateBackup)
			{
				string backupFilename = filename + "." + GlobalSettings.General.BackupExtension;
				if (File.Exists(backupFilename)) File.Delete(backupFilename);
				File.Move(filename, backupFilename);
			}

			if (BufferSettings.Encoding == null) BufferSettings.Encoding = System.Text.Encoding.Unicode;
			using (StreamWriter writer = new StreamWriter(filename, false, BufferSettings.Encoding))
			{
				writer.Write(Editor.Text);
			}
			BufferSettings.Filename = filename;
			Changed = false;
		}

		public void SaveFileAs()
		{
			FileExplorerForm frm = new FileExplorerForm();
			frm.AddMasks(GlobalSettings.General.Masks);
			frm.EnablePathChange = true;
			frm.FileMustExist = false;
			frm.MultiSelect = false;
			frm.SelectedMask = GlobalSettings.General.DefaultMask;
			frm.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			frm.Text = "Save File";
			if (frm.ShowDialog() == DialogResult.OK)
			{
				if (frm.SelectedFile.Length > 0)
				{
					SaveFile(Path.Combine(frm.SelectedPath, frm.SelectedFile));
				}
			}
		}
		

		void _editor_TextChanged(object sender, EventArgs e)
		{
			Changed = true;
		}

		void _bufferSettings_FilenameChanged(object sender, EventArgs e)
		{
			Text = Path.GetFileName(BufferSettings.Filename);
		}
	}
}
